package com.audi.activity;

import java.util.List;

import lib.relay.DevListInfo;
import lib.relay.RegistRelayFunc.SignUpStatus;
import lib.relay.RelayInterface;
import lib.relay.onAuthListener;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;
import com.audi.activity.SigninActivity.Loader;
import com.audi.box.objects.Authen;
import com.audi.box.objects.LocalData;
import com.audi.box.service.ConnectService;
import com.audi.handler.JSonparse;
import com.audi.handler.TrippleDes;

public class PreSignActivity extends Activity implements onAuthListener {

	private Context mContext;
	ImageButton btnSignin;
	public TextView txtSignIn;
	public EditText usergroup, passWord, userIdEmail;
	private ImageButton signUp;
	private ProgressDialog pDialog;
	private ProgressDialog m_DlgProgress = null;
	private String Tag2 = "register";

	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_pre_sign);
		RelayInterface.m_onAuthListener = this;
		txtSignIn = (TextView) findViewById(R.id.txt_sign_in);
		usergroup = (EditText) findViewById(R.id.user_group);
		userIdEmail = (EditText) findViewById(R.id.edt_email);
		passWord = (EditText) findViewById(R.id.edt_password);
		signUp = (ImageButton) findViewById(R.id.btn_signup);
		initView();
		initData();
		initListener();
	}

	private void initView() {

		SpannableStringBuilder text = new SpannableStringBuilder(
				getString(R.string.already_account));

		ClickableSpan clickableSpan = new ClickableSpan() {
			@Override
			public void onClick(View view) {

				// startActivity(new Intent(PreSignActivity.this,
				// SigninActivity.class));
				finish();
			}

			@Override
			public void updateDrawState(final TextPaint textPaint) {

				textPaint.setColor(PreSignActivity.this.getResources()
						.getColor(R.color.white));

				textPaint.setUnderlineText(true);
			}
		};
		text.setSpan(clickableSpan, 22, 29, 0);
		text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 22, 29, 0);
		txtSignIn.setMovementMethod(LinkMovementMethod.getInstance());

		// shove our styled text into the TextView
		txtSignIn.setText(text);

		btnSignin = (ImageButton) findViewById(R.id.btn_signin);

	}

	private void initData() {
		mContext = PreSignActivity.this;
	}

	private void initListener() {
		signUp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(userIdEmail.getText().toString().trim())) {
					Toast.makeText(mContext, "Please input email",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(usergroup.getText().toString().trim())) {
					Toast.makeText(mContext, "Please input User Name",
							Toast.LENGTH_SHORT).show();
					return;
				}
//				if (!Patterns.EMAIL_ADDRESS.matcher(
//						userIdEmail.getText().toString().trim()).matches()) {
//					Toast.makeText(mContext, "Email invalid",
//							Toast.LENGTH_SHORT).show();
//					return;
//				}
				if (TextUtils.isEmpty(passWord.getText().toString().trim())) {
					Toast.makeText(mContext, "Please input password",
							Toast.LENGTH_SHORT).show();
					return;
				}
//				if (passWord.getText().toString().length() < 8
//						|| passWord.getText().toString().length() > 25) {
//					Toast.makeText(mContext,
//							getString(R.string.password_not_empty),
//							Toast.LENGTH_SHORT).show();
//					return;
//				}
//				CreateProgressDialog("Register Account...");
//				RelayInterface.SignUp(userIdEmail.getText().toString(), passWord
//						.getText().toString(), usergroup.getText().toString());
				Loader signup = new Loader();
				signup.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
		});
	}

	@Override
	public void GetSignUp(final SignUpStatus mSignUpStatus) {
		runOnUiThread(new Runnable() {
			public void run() {
				DestroyProgressDialog();
				if (mSignUpStatus.status.equals("0")) {
					CreateProgressDialog("Login relay...");
					RelayInterface.GetRelaySAuth(userIdEmail.getText().toString(),
							passWord.getText().toString());
				} else {
					CreateWarningDialog(mSignUpStatus.content);
				}
			}
		});
	}

	@Override
	public void GetAuthFinished(boolean bValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void ListProfileFinished(List<DevListInfo> relay_list) {
		// TODO Auto-generated method stub

	}

	@Override
	public void LogoutFinished(boolean bValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void CBInit(boolean bValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void CBMakeCall(boolean bValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void CBHangUp(boolean bValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void CBDeInit(boolean bValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void CBClientSocket(String CBString) {
		// TODO Auto-generated method stub

	}

	private void CreateWarningDialog(String strMessage) {
		AlertDialog.Builder m_Builder = new AlertDialog.Builder(this);
		m_Builder.setTitle("Fail Register");
		m_Builder.setMessage(strMessage);
		m_Builder.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
		m_Builder.create().show();
	}

	private void CreateProgressDialog(String strMessage) {
		m_DlgProgress = new ProgressDialog(this);
		m_DlgProgress.setTitle(null);
		m_DlgProgress.setMessage(strMessage);
		m_DlgProgress.setIndeterminate(true);
		m_DlgProgress.setCancelable(true);
		m_DlgProgress.show();
	}

	private void DestroyProgressDialog() {
		if (m_DlgProgress != null)
			m_DlgProgress.dismiss();
	}
	private Authen model = null;

	public class Loader extends AsyncTask<Void, Void, Authen> {
		@Override
		protected void onPreExecute() {	
			super.onPreExecute();
			pDialog = new ProgressDialog(PreSignActivity.this);
			pDialog.setMessage("Logging in");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			Log.d(Tag2, "pdialog show");		
		}

		@Override
		protected Authen doInBackground(Void... arg0) {

			JSONObject jslogin = new JSONObject();
			JSONObject jslogin2 = new JSONObject();
			
			Log.d(Tag2, "Doinbackground");
			try {
				if (LocalData.isConnectsuccess == true) {
					Log.d(Tag2, "Send-1");
					
					try {
						
						jslogin2.put("group", usergroup.getText().toString());
						jslogin2.put(LocalData.TAG_USERNAME, userIdEmail.getText()
								.toString());
						String ecryptpass = TrippleDes.encrypt(passWord.getText().toString());
						jslogin2.put(LocalData.TAG_PASS, ecryptpass);
//						jslogin2.put(LocalData.TAG_PASS, passWord.getText());
						Log.d(Tag2, ""+ecryptpass);
						jslogin.put("tag","register");
						jslogin.put("strjson",jslogin2);
						Log.d(Tag2, "Put Json-2");
					} catch (JSONException e) {						
						Log.e(Tag2, "JSON failed-3" + e);
					}
					ConnectService.mmTcpClient.sendMessage(jslogin.toString());
					
					
					Log.d(Tag2, "JsonString: " + jslogin.toString());						
				}
				else {
					Log.e(Tag2, "Connect not success-4" + LocalData.isConnectsuccess);
				}
			} catch (Exception e) {
				Log.e(Tag2, "Fail parse Json-5" + e);
			}
			long startTime = System.currentTimeMillis();
			try {
				Log.d(Tag2, "Trước while" + LocalData.isregisted );				
				while ((System.currentTimeMillis()-startTime)<5000)
	  		{		
					if (LocalData.isregisted == true ) break;
//					Log.d(Tag2, "trong while" + LocalData.islogin );
	  		}
				}
			catch(Exception e)
			{
				Log.e(Tag2,""+e);
			}
			Log.d(Tag2, "end of doinbackground");	
			
			model =  JSonparse.getauthen(LocalData.strreceiver);
				return model;
		}

		@Override
		protected void onPostExecute(final Authen model) {
			Log.i("TESTTROLW", "TESTTROLW: 9");
			super.onPostExecute(model);// sfsmdf
			pDialog.dismiss();
			try {
				Log.d(Tag2,"in postexecute -1 " + LocalData.islogin);
				Log.d(Tag2,"Info " + model.getSuccess() + "---" + model.getTag() + " | "+ model.getUser_group());
				if (LocalData.isregisted==true) {
//					if (!model.getSuccess())
//					{
//						alertmess("Đăng nhập thất bại" +model.getSuccess() );
//					}
//					else {
						Log.d(Tag2, "On pregress update - 5");	
						Toast.makeText(PreSignActivity.this, "Đăng ký thành công", Toast.LENGTH_SHORT).show();
						Intent inhctr = new Intent(PreSignActivity.this,SigninActivity.class);
						startActivity(inhctr);
						finish();
//					}
				} else {
					alertmess("Đăng ký thất bại \nDữ liệu bị trùng lặp");
					}				
			} catch (Exception e) {
				e.printStackTrace();
				alertmess("Đăng nhập thất bại-3");
				Log.d(Tag2,"in postexecute -2 "+e);
			}
		}
		
	}
	void alertmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						return;
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	void alertfailmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
}